import user from '../../utils/user'
import {
    goAppList,
    goToContract,
    dateFormat
} from '../../utils/util'
import {
    getisnewmessageapi
} from '../../api/app'
import {
    getContractList
} from '../../api/contract'
import global from '../../utils/global'
import {
    getBannerList
} from '../../api/job'

import {
    getJobList,
    getWaitTimeline,
    getWaitJobList,
    getApplyJobList,
    applyJob,
    getJobApplyDate
} from '../../api/job'
const app = getApp()
Page({
    data: {
        isactive: false,
        isAttention: true,
        tabActive: 0,
        jobList: [],
        recordList: [],
        waitList: [],
        today: '',
        disableList: {},
        reportJobId: '',
        reportJob: {
            dateStart: '',
            dateEnd: '',
            workType: ''
        },
        todo: false,
        applyState: ['等待领队确认', '领队已确认', '领队已拒单', '已取消'],
        applyStateColor: ['yellow', 'green', 'red', 'grey'],
        wechatGroupUrl: 'https://work.weixin.qq.com/gm/00c7abf6b951631c446c85998d595d06',
        movableX: '580rpx',
        movableY: '900rpx',
        refreshKey: 1,
        jobInfo: {},
        userHeadUrl: '',
        userName: '',
        bannerList: [],
        isLogin: false,
        srcolling: false,
        timer: null,
    },
    static: {
        hasJobNext: true,
        jobPageNum: 1,
        jobPageSize: 10,
        hasRecordNext: true,
        recordPageNum: 1,
        recordPageSize: 20,
    },
    async onLoad(option) {
        this.getBannerList()
        await user.waitLogin()
        console.log(user.userName, user.avatarUrl, 'user内容')
        this.setData({
            userName: user.userName,
            userHeadUrl: user.avatarUrl,
            isLogin: true
        })
        console.log(this.data.userName, this.data.userHeadUrl, '赋值')
        if (option)
            if (option.scene) {
                wx.navigateTo({
                    url: '/pages/join/join?scene=' + option.scene,
                })
            }
        if (app.globalData.wechatGroup)
            this.setData({
                wechatGroupUrl: app.globalData.wechatGroup
            })

        if (app.globalData.wechatGroup)
            this.setData({
                wechatGroupUrl: app.globalData.wechatGroup
            })
        let res = await getisnewmessageapi()
        console.log(res, 'csj')
        this.setData({
            // isactive: falsetomessage
            isactive: res
        })
    },
    async onShow() {
        this.getTabBar().setData({
            selected: 0
        })
        try {
            await user.waitLogin()
            this.setData({
                userId: user.userId,
                isAttention: user.isAttention,
                isLogin: true
            })
            this.reLoad()
        } catch (err) {
            this.setData({
                userId: '',
                isAttention: false,
            })
            // await app.confirm('您还未登录，是否立即登录？')
            // user.goRegister()
        }
        let res = await getisnewmessageapi()
        console.log(res, 'csj')
        this.setData({
            isactive: res
        })
    },
    // 去消喜页面
    tomessage() {
        console.log('去消息页面')
        wx.navigateTo({
            url: '/pages/message/message',
        })
    },
    // 去详情页
    goWorkDetail(event) {
        console.log(event.detail.item, 'event')
        this.setData({
            jobInfo: event.detail.item
        })
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + this.data.jobInfo.id
        })
    },
    onPullDownRefresh() {
        this.setData({
            refreshKey: 0
        })
        setTimeout(() => {
            this.setData({
                refreshKey: Math.ceil(Math.random() * 1000000)
            })
        }, 100)
        this.reLoad()
        wx.stopPullDownRefresh()
    },
    reLoad() {
        getContractList().then(this.tipContract)
        this.setData({
            jobList: []
        })
        this.static.hasJobNext = true
        this.static.jobPageNum = 1
        this.getJob(true, true)
    },
    // 获取招聘中岗位列表
    async getJob(empty = false, reRendering) {
        if (!this.static.hasJobNext) {
            return
        }
        if (empty) {
            this.setData({
                jobList: [],
            })
            this.static.jobPageNum = 1
        }
        const result = await getJobList({
            pageNum: this.static.jobPageNum,
            pageSize: this.static.jobPageSize
        })
        this.static.hasJobNext = result.hasNextPage
        this.static.jobPageNum += 1

        this.setData({
            jobList: result.list.map(item => {
                item.jobTag = item.jobTag ? item.jobTag.split(';') : []
                item.jobDetail = item.jobDetail.replace(/[\r\n]/g, '「').split('「').filter(item => item)
                return item
            })
        })
        console.log(this.data.jobList, 'jobListjobList')
        wx.lin.renderWaterFlow(this.data.jobList, reRendering, (res) => {})
    },
    // 获取待上班时间轴
    async updateTimeline(event) {
        if (global.token) {
            const date = new Date(event.detail.date)
            const result = await getWaitTimeline({
                beginTime: event.detail.date,
                endTime: dateFormat('YYYY-mm-dd', new Date(date.setDate(date.getDate() + (event.detail.type === 'week' ? 6 : 30))))
            })
            this.setData({
                todo: result
            })
        }
    },
    // 获取待上班列表
    async getWaitJobList(date) {
        if (global.token && !this.data.todo || this.data.todo[date?.detail ?? date]) {
            const result = await getWaitJobList({
                workDate: date?.detail ?? date
            })
            this.setData({
                waitList: result.list.map(item => {
                    item.jobTag = item.jobTag ? item.jobTag.split(';') : []
                    return item
                })
            })
            return 0
        } else {
            this.setData({
                waitList: []
            })
        }

    },
    // 获取报名记录
    async getRecord() {
        if (!this.static.hasRecordNext) {
            return
        }
        const result = await getApplyJobList({
            pageNum: this.static.recordPageNum,
            pageSize: this.static.recordPageSize
        })
        console.log(result)
        this.static.hasRecordNext = result.hasNextPage
        this.static.recordPageNum += 1
        this.data.recordList.push(...result.list.map(item => {
            item.jobTag = item.jobTag ? item.jobTag.split(';') : []
            return item
        }))
        console.log(this.data.recordList)
        this.setData({
            recordList: this.data.recordList
        })
        console.log(this.data.recordList, 'recordList')

    },
    onShareAppMessage() {
        app.toast('分享成功，感谢您的支持！')
        return {
            title: user.userName + '邀请您一起使用子弹云发工资！',
            imageUrl: '/assets/img/home/share.png'
        }
    },
    // 点击报名
    async onApplyJob(event) {
        const job = this.data.jobList[event.currentTarget.dataset.index]
        const result = await getJobApplyDate({
            jobId: job.id
        })

        this.setData({
            reportJobId: job.id,
            ['reportJob.dateStart']: job.jobBeginDay,
            ['reportJob.dateEnd']: job.jobEndDay,
            ['reportJob.workType']: job.workType,
            disableList: result.applyDate
        })
    },
    attention() {
        goAppList([{
            url: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa68344cdd579b406&redirect_uri=https://front.51zidan.com/mini-auth/bullet.html?' + encodeURIComponent('openid=' + user.openid) + '&response_type=code&scope=snsapi_base#wechat_redirect',
            time: 3000
        }, {
            url: 'https://mp.weixin.qq.com/s/9SgP2C0QTwOu2AVZoJMp1Q',
            type: 'redirectTo' // 重定向跳转到关注页面，用户少返回一个界面
        }])
        this.setData({
            isAttention: true,
        })
    },
    tipContract(res) {
        // // 闭包访问上级对象
        // const contract = (num)=>{
        // 	if(num === res.length){ // 递归结束条件
        // 		return 
        // 	}
        if (res.length === 0) {
            // isContract = false
            return
        }
        app.confirm(`您有${res.length}份合同待签署，是否立即签署`).then(() => {
            // console.log(res[0].flowPath)
            goToContract(res[0].flowPath, res[0].id)
            // contract(num+1)
        }, () => {
            // isContract = false
        })
        // }
        // contract(0)
    },
    async onTab(event) {
        this.setData({
            tabActive: event.detail
        })
        if (global.token) {
            this.reLoad()
        }
    },
    async reportDateSelected(event) {
        console.log(event.detail)
        const result = applyJob({
            jobId: this.data.reportJobId,
            applyTimeList: event.detail
        })
        wx.navigateTo({
            url: '/pages/job-status/job-status?id=' + result[0],
            events: {},
            success(res) {
                res.eventChannel.emit('reportDate', {
                    data: event.detail
                })
            }
        })
        this.setData({
            reportJobId: ''
        })
    },
    reportDateCancel() {
        this.setData({
            reportJobId: ''
        })
    },
    goReportRecord(event) {
        wx.navigateTo({
            url: '/pages/job-status/job-status?id=' + event.currentTarget.dataset.id
        })
    },
    goJobDetail(event) {
        wx.navigateTo({
            url: '/pages/job-detail/job-detail?id=' + event.currentTarget.dataset.id
        })
    },
    onMovable(event) {
        this.setData({
            movableX: '580rpx',
            movableY: event.detail.y
        })
    },
    // 到达底部触发
    onReachBottom() {
        console.log('到达底部了')
        if (!this.static.hasJobNext) {
            return
        }
        this.static.jobPageNum += 1
        this.getJob(false, false)
    },
    getBannerList() {
        getBannerList({
            configKey: 'blue_banner_info'
        }).then(res => {
            console.log(111, res)
            if (res) {
                const list = JSON.parse(res)
                console.log(333, list)
                this.setData({
                    bannerList: list
                })
            }
        })
    },
    onPageScroll(e) {
        this.setData({
            srcolling: true
        })
        if (this.data.timer) clearTimeout(this.data.timer)
        this.data.timer = setTimeout(() => {
            this.setData({
                srcolling: false
            })
        }, 1000)
    },
    handleJump(ev) {
        const dataset = ev.currentTarget.dataset
        wx.reportEvent('home_banner_click', {
            'enroll_number': 1
        })
        wx.navigateTo({
            url: '/pages/web-view/web-view',
            success: (res) => {
                res.eventChannel.emit('data', {
                    path: dataset.url
                })
            }
        })
    },
    text() {
        wx.navigateToMiniProgram({
            appId: 'wx850e3a22db40acac',
            path: '/pages/index/index'
        })
    }
})